//
//  ViewController.m
//  ExcelToPlist
//
//  Created by 赵梁 on 2017/3/27.
//  Copyright © 2017年 赵梁. All rights reserved.
//

#import "ViewController.h"

#import "ExcelReader.h"
#import "ConvertKeySettingManager.h"
#import "ConvertKeyModel.h"

@interface ViewController ()<NSTableViewDelegate,NSTableViewDataSource>
{
    NSArray *_xlsList;
}

@property (weak) IBOutlet NSTextField *xlsPathTF;
@property (weak) IBOutlet NSTextField *jsonPathTF;

@property (weak) IBOutlet NSTextField *noticeLabel;

@property (weak) IBOutlet NSTableView *xlsTableView;

@end

@implementation ViewController

- (void)loadView
{
    [super loadView];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}

- (void)viewDidAppear
{
    [super viewDidAppear];
}

- (void)loadDataFile:(NSString*)file
{
    [self loadLog:file];
    _xlsList = [ExcelReader JSONArrayWithExcelFilePath:file];
    [self reloadData];
}

- (void)reloadData
{
    if (_xlsList.count>0) {
        
        NSArray *keys = [_xlsList[0] allKeys];
        
        keys = [keys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2];
        }];
        
        NSInteger index = 0;
        for (NSString *key in keys) {
            if ([_xlsTableView tableColumnWithIdentifier:key]) {
                continue;
            }
            
            NSTableColumn *colums = [[NSTableColumn alloc]initWithIdentifier:key];
            colums.minWidth = 40;
            colums.title = key;
            [_xlsTableView addTableColumn:colums];
            
            index++;
        }
    }
    _xlsTableView.dataSource = self;
    _xlsTableView.delegate = self;
    [_xlsTableView reloadData];
}

- (void)loadLog:(NSString*)log
{
    _noticeLabel.stringValue = log;
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

- (IBAction)xlsFileSelect:(NSButton *)sender {
    [self openToSelectXls];
}

- (IBAction)jsonFilePathSelect:(NSButton *)sender {
    [self openToSelectExportFile];
}

- (IBAction)exportJson:(id)sender {
    //1 . 判断file
    //1.1 长度>0
    NSString *filePath = _jsonPathTF.stringValue;
    if (!(filePath.length>0)) {
        //TODO 提示用户去选择文件夹
        return;
    }
    
    //1.2 是文件夹还是文件
    //1.2.1 建文件夹，建文件夹是否存在，不存在创建文件夹
    //1.2.2 文件，建文件夹是否存在，不存在创建文件夹
    //判断文件夹是否存在
    //2 创建文件
    
    NSString *directory = filePath;
    if ([directory pathExtension].length>0) {
        directory = [directory stringByDeletingLastPathComponent];
    }else {
        filePath = [filePath stringByAppendingPathComponent:@"default.txt"];
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = YES;
    if (![fileManager fileExistsAtPath:directory isDirectory:&isDir]) {
        [fileManager createDirectoryAtPath:directory withIntermediateDirectories:NO attributes:nil error:nil];
    }
    
    //3 向文件写入数据
    NSArray *data = [self convertXLSJSONToExportData:_xlsList];
    NSString *jsonStr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:data options:0 error:nil] encoding:NSUTF8StringEncoding];
    NSError *error;
    @try {
        BOOL success = [jsonStr writeToFile:filePath atomically:yearMask encoding:NSUTF8StringEncoding error:&error];
        if (success) {
            [self loadLog:[NSString stringWithFormat:@"导出成功：%@",filePath]];
        }else {
            [self loadLog:[NSString stringWithFormat:@"导出失败：%@ error: %@",filePath, error]];
        }
    }
    @catch (NSException * e) {
        //TODO: error handling maybe
    }
}

- (NSArray*)convertXLSJSONToExportData:(NSArray*)xlsJson
{
    NSArray *returnArray = [xlsJson copy];
    //1.取出配置的数据
    //按顺序取第一个，目标key为空或者nil，或者已存在的key，可能会出现异常
    NSArray<ConvertKeyModel*> *convertKetList = [ConvertKeySettingManager loadConfigFromDisc];
    if (convertKetList.count>0) {
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dic in returnArray) {
            
            NSMutableDictionary *mutableDic = [dic mutableCopy];
            for (ConvertKeyModel *keyModel in convertKetList) {
                if (keyModel.keyOld.length>0&&keyModel.keyNew.length>0) {
                    id val = [mutableDic valueForKey:keyModel.keyOld];
                    [mutableDic setValue:nil forKey:keyModel.keyOld];
                    [mutableDic setValue:val forKey:keyModel.keyNew];
                }
            }
            [mutableArray addObject:mutableDic];
        }
        return mutableArray;
    }else {
        return returnArray;
    }
}

#pragma mark - tableViewDatasource

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return [_xlsList count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSString* columnIdentifier = [tableColumn identifier];
    //NSLog(@"%@", columnIdentifier);
    NSDictionary *dic = [_xlsList objectAtIndex:row];
    id val = [dic valueForKey:columnIdentifier];
    return [NSString stringWithFormat:@"%@",val];
}

- (void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSString* identifier = [tableColumn identifier];
    NSDictionary *dic = [_xlsList objectAtIndex:row];
    [dic setValue:object forKey:identifier];
}

- (nullable NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row NS_AVAILABLE_MAC(10_7)
{
    NSString* identifier = [tableColumn identifier];
    
    NSTableCellView *cell = [tableView makeViewWithIdentifier:@"A" owner:nil];
    if( [cell isKindOfClass:[NSTableCellView class]] ){
        NSDictionary *dic = [_xlsList objectAtIndex:row];
        id val = [dic valueForKey:identifier];
        
        cell.textField.stringValue = [NSString stringWithFormat:@"%@",val];
        return cell;
    }
    return nil;
}

- (void)openToSelectXls
{
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    NSArray* fileTypes = [[NSArray alloc] initWithObjects:@"xls", nil];
    [panel setMessage:@"select a file"];
    [panel setPrompt:@"OK"];
    [panel setCanChooseDirectories:NO];
    [panel setCanCreateDirectories:YES];
    
    [panel setCanChooseFiles:YES];
    [panel setAllowsMultipleSelection:NO];
    
    [panel setAllowedFileTypes:fileTypes];
    
    //显示
    [panel beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result) {
        
        //是否点击open 按钮
        if (result == NSModalResponseOK) {
            //NSURL *pathUrl = [panel URL];
            NSString *filePath = [panel.URLs.firstObject path];
            
            _xlsPathTF.stringValue = filePath;
            
            
            [self loadDataFile:filePath];
            
            filePath = [filePath stringByDeletingPathExtension];
            filePath = [filePath stringByAppendingPathExtension:@"txt"];
            _jsonPathTF.stringValue = filePath;
        }
    }];
}

- (void)openToSelectExportFile
{
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    NSArray* fileTypes = [[NSArray alloc] initWithObjects:@"txt",@"text", nil];
    [panel setMessage:@"select a file or a directory"];
    [panel setPrompt:@"OK"];
    [panel setCanChooseDirectories:YES];
    [panel setCanCreateDirectories:YES];
    [panel setCanChooseFiles:YES];
    [panel setAllowsMultipleSelection:NO];
    [panel setAllowedFileTypes:fileTypes];
    
    //显示
    [panel beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result) {
        
        //是否点击open 按钮
        if (result == NSModalResponseOK) {
            //NSURL *pathUrl = [panel URL];
            NSString *filePath = [panel.URLs.firstObject path];
            
            _jsonPathTF.stringValue = filePath;
        }
    }];
}



@end
